import React from 'react'
import Utils from '../../utils/utils'
import { Card, Pagination, Table } from 'antd'
import "./index.less"

/**
 * @param updateSelectedItem 行点击通用函数
 * @param rowSelection 行选中的类型（checkbox、radio）
 * @param selectedRowKeys 选中行的索引 
 * @param selectedItem 选中行对象
 * @param selectedIds 选中行的Id
 */
export default class ETable extends React.Component {
    state = {}

    /** 处理行点击事件 */
    onRowClick = (record, index) => {
        let rowSelection = this.props.rowSelection;
        if (rowSelection == 'checkbox') {
            let selectedRowKeys = this.props.selectedRowKeys;
            let selectedIds = this.props.selectedIds;
            let selectedItem = this.props.selectedItem || [];
            if (selectedIds) {
                const i = selectedIds.indexOf(record.id);
                if (i == -1) {//避免重复添加
                    selectedIds.push(record.id)
                    selectedRowKeys.push(index);
                    selectedItem.push(record);
                } else {
                    selectedIds.splice(i, 1);
                    selectedRowKeys.splice(i, 1);
                    selectedItem.splice(i, 1);
                }
            } else {
                selectedIds = [record.id];
                selectedRowKeys = [index]
                selectedItem = [record];
            }
            this.props.updateSelectedItem(selectedRowKeys, selectedItem, selectedIds);
        } else {
            let selectKey = [record.id];
            this.props.updateSelectedItem(selectKey, record);
        }
    };

    // 选择框变更
    onSelectChange = (selectedRowKeys, selectedRows) => {
        let rowSelection = this.props.rowSelection;
        const selectedIds = [];
        if (rowSelection == 'checkbox') {
            selectedRows.map((item) => {
                selectedIds.push(item.id);
            });
            this.setState({
                selectedRowKeys,
                selectedIds: selectedIds,
                selectedItem: selectedRows[0]
            });
        }
        this.props.updateSelectedItem(selectedRowKeys, selectedRows[0], selectedIds);
    };

    /** 选中所有 */
    onSelectAll = (selected, selectedRows, changeRows) => {
        let selectedIds = [];
        let selectKey = [];
        selectedRows.forEach((item, i) => {
            selectedIds.push(item.id);
            selectKey.push(i);
        });
        this.props.updateSelectedItem(selectKey, selectedRows[0] || {}, selectedIds);
    }

    /** 获取分页参数 */
    getParams = pagination => ({
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
    });

    /** Table分页、排序、筛选事件的响应函数 */
    handleTableChange = (pagination, filtersArg, sorter) => {
        const { handleRead } = this.props;
        const sort = {};
        const page = this.getParams(pagination);
        const payload = {
            ...page,
            // ...searchFormValues,
        };

        if (sorter && sorter.field) {
            const sortVal = `${sorter.field} ${sorter.order === 'ascend' ? 'asc' : 'desc'}`;
            sort.sort = sortVal;
        }
        // setPage(page);
        // setSort(sort);
        // tableRef.current.cleanSelectedKeys();
        return handleRead({
            ...sort,
            ...payload,
        });
    };

    getOptions = () => {
        let p = this.props;
        const name_list = {
            "订单编号": 170,
            "车辆编号": 80,
            "手机号码": 96,
            "用户姓名": 70,
            "密码": 70,
            "运维区域": 300,
            "车型": 42,
            "故障编号": 76,
            "代理商编码": 97,
            "角色ID": 64
        };
        if (p.columns && p.columns.length > 0) {
            p.columns.forEach((item) => {
                //开始/结束 时间
                if (!item.title) {
                    return
                }
                if (!item.width) {
                    if (item.title.indexOf("时间") > -1 && item.title.indexOf("持续时间") < 0) {
                        item.width = 132
                    } else if (item.title.indexOf("图片") > -1) {
                        item.width = 86
                    } else if (item.title.indexOf("权限") > -1 || item.title.indexOf("负责城市") > -1) {
                        item.width = '40%';
                        item.className = "text-left";
                    } else {
                        if (name_list[item.title]) {
                            item.width = name_list[item.title];
                        }
                    }
                }
                item.bordered = true;
            });
        }

        const {
            data,
            selectedRowKeys,
            showPagination = true,
        } = this.props;
        const { list = [], pagination = false } = data || {};

        const rowSelection = {
            type: 'radio',
            selectedRowKeys,
            onChange: this.onSelectChange,
            onSelect: (record, selected, selectedRows) => {
                console.log('...')
            },
            onSelectAll: this.onSelectAll
        };
        let row_selection = this.props.rowSelection;
        // 当属性未false或者null时，说明没有单选或者复选列
        if (row_selection === false || row_selection === null) {
            row_selection = false;
        } else if (row_selection == 'checkbox') {
            //设置类型未复选框
            rowSelection.type = 'checkbox';
        } else {
            //默认未单选
            row_selection = 'radio';
        }

        /** 分页 */
        const paginationProps =
            pagination && showPagination
                ? {
                    showSizeChanger: true,
                    showQuickJumper: true,
                    // position: 'top',
                    style: {
                        marginTop: '5px',
                        height: 32,
                        // marginBottom: '16px',
                        float: 'right',
                        backgroundColor: 'white',
                    },
                    showTotal: (total, range) => `显示 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                    onChange: (current, pageSize) => this.handleTableChange({ current, pageSize }, null, null),
                    onShowSizeChange: (current, pageSize) => this.handleTableChange({ current, pageSize }, null, null),
                    ...pagination,
                }
                : false;

        let { columns: axcolumns } = this.props;
        if (
            axcolumns &&
            axcolumns.findIndex(f => f.dataIndex === 'ax_empty_data_index') === -1
        ) {
            axcolumns.push({
                title: '',
                dataIndex: 'ax_empty_data_index',
                sorter: false,
                ellipsis: true,
            });
        }

        return (
            <Card>
                <Table
                    bordered
                    // size='small'
                    rowKey={record => record.id}
                    className="card-wrap page-table"
                    dataSource={list}
                    pagination={false}
                    {...this.props}
                    columns={axcolumns}
                    rowSelection={row_selection ? rowSelection : null}
                    scroll={{ x: 'fit-content' }}
                    onRow={(record, index) => ({
                        onClick: () => {
                            if (!row_selection) {
                                return;
                            }
                            this.onRowClick(record, index)
                        }
                    })}
                />
                <Pagination pageSizeOptions={['10', '20', '30', '40']} {...paginationProps} />
            </Card>
        )
    };
    render = () => {
        return (
            <div>
                {this.getOptions()}
            </div>
        )
    }
}